package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.dao.OrderDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.service.OrderService;
import com.lkd.vo.PartnerVO;
import com.lkd.vo.PayVO;
import com.lkd.vo.SkuVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    @Autowired
    private VMService vMService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public OrderEntity getByOrderNo(String orderNo) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(OrderEntity::getOrderNo, orderNo);
        return this.getOne(qw);
    }

    /**
     * 创建订单
     *
     * @param payVO 封装的支付对象
     * @return
     */
    @Override
    public OrderEntity createOrder(PayVO payVO) {
        //远程调用vmService.hasCapacity 判断是否有库存
        if (!vMService.hasCapacity(payVO.getInnerCode(), Long.parseLong(payVO.getSkuId()))) {
            throw new LogicException("该商品已售罄");
        }

        //构建实体类OrderEntity，售货机相关信息通过 vmService.getVMInfo获得
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOpenId(payVO.getOpenId());//微信用户OpenId
        orderEntity.setPayStatus(VMSystem.PAY_STATUS_NOPAY);//订单支付状态未支付

        orderEntity.setOrderNo(payVO.getInnerCode() + System.nanoTime());//订单编号

        //根据售货机编号查询售货机信息，并赋值给订单对象
        VmVO vm = vMService.getVMInfo(payVO.getInnerCode());
        BeanUtils.copyProperties(vm, orderEntity);
        orderEntity.setAddr(vm.getNodeAddr());

        //根据商品编号查询商品信息，并复制给订单对象
        SkuVO sku = vMService.getSku(payVO.getSkuId());
        BeanUtils.copyProperties(sku, orderEntity);
        orderEntity.setAmount(sku.getRealPrice());
        orderEntity.setStatus(VMSystem.ORDER_STATUS_CREATE);

        //通过userService.getPartner 获得合作商，使用提成比例计算分成
        PartnerVO partner = userService.getPartner(vm.getOwnerId());
        //计算合作商分账金额
        BigDecimal bg = new BigDecimal(sku.getRealPrice());
        int bill = bg
                .multiply(new BigDecimal(partner.getRatio()))
                .divide(new BigDecimal(100), 0, RoundingMode.HALF_UP)
                .intValue();
        orderEntity.setBill(bill);

        this.save(orderEntity);


        OrderCheck orderCheck = new OrderCheck();
        orderCheck.setOrderNo(orderEntity.getOrderNo());
        try {
            mqttProducer.send("$delayed/600/" + TopicConfig.ORDER_CHECK_TOPIC, 2, orderCheck);
        } catch (JsonProcessingException e) {
            log.error("发送延迟订单消息出错", e);
        }


        return orderEntity;
    }

}
